package com.ebraga.trackerclub.android.view.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView;

import com.ebraga.trackerclub.android.R;
import com.ebraga.trackerclub.android.util.AndroidApplication;
import com.ebraga.trackerclub.android.util.DLog;
import com.ebraga.trackerclub.android.util.DateUtils;
import com.ebraga.trackerclub.android.util.ISmartServiceConstants;
import com.ebraga.trackerclub.android.util.SmartServiceJavascriptInterface;
import com.ebraga.trackerclub.android.util.UtilView;
import com.ebraga.trackerclub.android.util.WebServiceTask;
import com.ebraga.trackerclub.android.view.MainActivity;
import com.ebraga.trackerclub.android.view.MyWebViewClient;
import com.ebraga.trackerclub.android.vo.PositionVO;

/**
 * Fragment that appears in the "content_frame"
 */
@SuppressLint("SetJavaScriptEnabled")
public class CheckInOutFragment extends Fragment {
	WebView webView;
	Date lastGpsMessage 				= null;
	final int TIME_SHOW_GPS_MESSAGE 	= 15;
	
    public CheckInOutFragment() {
        // Empty constructor required for fragment subclasses
    	
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    	
    	try {
    		getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    	} catch (Exception e) {
    		DLog.e(e);
    	}

    	
    	((MainActivity)getActivity()).setCurrentScreen(ISmartServiceConstants.SCREEN_TAG.CHECKINOUT);
    	
    	View mainView = (View) inflater.inflate(R.layout.fragment_webview, container, false);
        webView = (WebView) mainView.findViewById(R.id.webview);
        webView.setWebViewClient(new MyWebViewClient());
        webView.getSettings().setBuiltInZoomControls(false);
        webView.getSettings().setSupportZoom(false);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JavascriptInterface(inflater.getContext()), "AndroidNativeCode");
       	webView.loadUrl("file:///android_asset/map.html");
       	//webView.loadUrl("http://www.google.com.br");
        
        return mainView;
    }
    

    private class WSTask extends WebServiceTask<String> {

	    public WSTask(String requestMethod) {
			super(getActivity().getBaseContext(), requestMethod);
		}

		@Override
	    protected void onPostExecute(String response) {
			
	    	super.onPostExecute(response);
	    	
	    	webView.loadUrl("javascript:setAllPosition(" + response + ")");
	    	
	    }		
   		
   	}    
    
	public class JavascriptInterface extends SmartServiceJavascriptInterface {
		 
		public JavascriptInterface(Context c) {
			super(c);
		}

		public void getAllUserPosition() {
			WSTask wsTask = new WSTask(ISmartServiceConstants.REQUEST_METHOD.POST);

			List<String> lst = new ArrayList<String>();
			lst.add("");
			wsTask.setLstObject(lst);
			wsTask.execute(ISmartServiceConstants.WEBSERVICE_URL.LIST_POSITIONS_URL);
		}

		public void getGpsInfo() {
			try {
				
				JSONObject jObject = getAllGpsInfo();
				webView.loadUrl("javascript:setGpsInfo(" + jObject + ")");

			} catch (Exception e) {
				DLog.e(e);
				controlMessageGps();
				
			}

		}
		
		public void getSpeedInfo() {
			try {
				
				JSONObject jObject = getAllGpsInfo();
				webView.loadUrl("javascript:setSpeedInfo(" + jObject + ")");

			} catch (Exception e) {
				DLog.e(e);
				controlMessageGps();
				
			}

		}		

		private JSONObject getAllGpsInfo() throws JSONException {
			JSONObject jObject = new JSONObject();
			
			if (!UtilView.checkRestriction(getActivity().getApplicationContext())) {
				webView.loadUrl("file:///android_asset/restriction.html");
			} else {
			
				AndroidApplication androidApplication = (AndroidApplication) getActivity().getApplicationContext();
				PositionVO gpsInfoVO = (PositionVO) androidApplication.getGpsInfoVO();

				Double speed = 0.0;
				try {
					speed = Double.parseDouble(gpsInfoVO.getSpeed());
				
				} catch (Exception e) {
					speed = 0.0;
				}
				
				jObject.put("Imei", gpsInfoVO.getImei());
				jObject.put("Latitude", gpsInfoVO.getLatitude());
				jObject.put("Longitude", gpsInfoVO.getLongitude());
				jObject.put("Accuracy", gpsInfoVO.getAccuracy());
				jObject.put("Provider", gpsInfoVO.getProvider());
				jObject.put("Speed", speed.intValue());
				
			}
			return jObject;
		}
		



		private void controlMessageGps() {

			if ((lastGpsMessage == null) || (DateUtils.diffBetweenDate(lastGpsMessage, new Date(), Calendar.SECOND) > TIME_SHOW_GPS_MESSAGE)) {
				lastGpsMessage = new Date();			
				UtilView.showMessage(webView, getActivity().getApplicationContext(), ISmartServiceConstants.ERROR_CODE.WAIT_GPS_POSITION);
			}
			
		}
	

	}
	
}